package com.algorithm.basic;/*
 *@Author:DOWN
 *@Date:2021/12/11 15:57
 *@Comment:选择排序 每一次循环找到最小/大的数 修改位置
 */
import com.algorithm.testutils.ArrayGenerator;
import com.algorithm.testutils.SortingHelp;
import java.util.Arrays;

public class SelectionSort {
    public static void main(String[] args) throws Exception {
        Integer[] tests= ArrayGenerator.getRandomArrays(100000,100000000);
        SortingHelp.sortTest("com.algorithm.yyy.SelectionSort","sort",tests);
    }
    private static <E extends Comparable<E>> E searchMin(E[] arrs) {
        E min = arrs[0];
        //查最小数。
        for (int i = 1; i < arrs.length; i++) {
            if (min.compareTo(arrs[i])>0) {
                min = arrs[i];
            }
        }
        return min;
    }
    //选择排序（标准方法）
    public static <E extends Comparable<E>> void sort(E[] arrs) {
        for (int i = 0; i < arrs.length - 1; i++) {
            //记录初始化下标
            int index = i;
            //循环遍历最小值下标
            for (int k = i + 1; k < arrs.length; k++) {
                if (arrs[index].compareTo(arrs[k])>0) {
                    index = k;
                }
            }
            //下标不一致，交换索引对应内存值
            if (index != i) {
                E item=arrs[index];
                arrs[index] = arrs[i];
                arrs[i] = item;
            }
        }
    }
    //选择排序（逆序方法）
    public static <E extends Comparable<E>> void reverseSort(E[] arrs){
        System.out.println(Arrays.toString(arrs));
        for (int i = arrs.length-1; i >=0; i--) {
            //记录初始化下标
            int index = i;
            //循环遍历最小值下标
            for (int k = i - 1; k >=0; k--) {
                if (arrs[k].compareTo(arrs[index])>0) {
                    index = k;
                }
            }
            //下标不一致，交换索引对应内存值
            if (index != i) {
                E item=arrs[index];
                arrs[index] = arrs[i];
                arrs[i] = item;
            }
        }
        System.out.println(Arrays.toString(arrs));
    }
}
